package com.es.interpreter.config;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.setting.Setting;
import lombok.Getter;
import lombok.Setter;

import java.util.HashMap;
import java.util.Map;

/**
 * 解释器配置类，注意该配置方法为单例实现
 *
 * @author Will
 */
@Getter
@Setter
public class IntepretConfig {
    private static volatile IntepretConfig instance = null;

    private IntepretConfig() {
    }

    /**
     * 是否初始化
     */
    private boolean issInit = false;
    /**
     * 配置文件相对路径
     */
    private String configRelativePath;
    /**
     * 配置文件属性
     */
    private Setting setting;
    /**
     * 默认解释实现
     */
    private String defaultExpression;
    /**
     * 默认解释实现全类名
     */
    private String defaultExpressionClass;
    /**
     * 各解释器实现自定义参数
     */
    private Map<String, Object> customParam;

    /**
     * 单例实现
     *
     * @return instance
     */
    public static IntepretConfig getInstance() {
        if (instance == null) {
            synchronized (IntepretConfig.class) {
                if (instance == null) {
                    instance = new IntepretConfig();
                }
            }
        }
        return instance;
    }

    /**
     * 初始化为JavaScript解释
     *
     * @return 返回当前对象
     */
    public IntepretConfig init2JavaScript() {
        this.init();

        String group = "javascriptExpression";
        String javascriptExpressionClass = this.setting.get(group, "javascriptExpressionClass");
        String javascriptExFile = this.setting.get(group, "javascriptExFile");

        // 以flag作为后续判断标识，判断是否有该配置项
        this.customParam.put("javascriptFlag", true);
        this.customParam.put("javascriptExpressionClass", javascriptExpressionClass);
        this.customParam.put("javascriptExFile", javascriptExFile);

        return this;
    }

    /**
     * 初始化赋值
     */
    private void init() {
        if (this.issInit) {
            return;
        }

        // 赋值基础属性
        this.configRelativePath = new ClassPathResource("config/intepret.setting").getPath();
        this.setting = new Setting(FileUtil.touch(this.configRelativePath), CharsetUtil.CHARSET_UTF_8, true);
        this.defaultExpression = this.setting.get("defaultExpression");
        this.defaultExpressionClass = this.setting.get("defaultExpressionClass");
        this.customParam = new HashMap<String, Object>(16);

        this.issInit = true;
    }
}
